package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ProducerPublish {
    //队列名称
    private static final String QUEUE_INFORM_EMAIL = "queue_info_email";
    private static final String QUEUE_INFORM_SMS = "queue_info_sms";
    private static final String EXCHANGE_FANOUT_INFORM="exchange_fanout_inform";
    public static void main(String[] args) throws IOException, TimeoutException {
        // 通过连接工厂创建新得连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 设置连接地址和端口
        connectionFactory.setHost("192.168.255.129");
        connectionFactory.setPort(5672);
        // 设置连接账户
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        // 设置虚拟机
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        Channel channel = null;
        try {
            // 建立新连接
            connection =connectionFactory.newConnection();
            // 建立通道
            channel = connection.createChannel();
            // 声明队列,如果队列在mq中没有就要创建
            /**
             * arg1:队列名称
             * arg2:是否持久化，重启后队列还在
             * arg3:是否独占连接,该连接只能该队列访问，如果独占连接关闭自动删除队列
             * arg4:自动删除,队列不再使用是否自动删除
             * arg5:可以设置一些队列得扩展参数，比如存活时间等
             */
            channel.queueDeclare(QUEUE_INFORM_EMAIL,true,false,false,null);
            channel.queueDeclare(QUEUE_INFORM_SMS,true,false,false,null);
            //声明交换机
            /**
             * arg1:交换机名称
             * arg2：交换机类型
             * BuiltinExchangeType为rabbitmq提供的枚举类，对应交换机模式
             */
            channel.exchangeDeclare(EXCHANGE_FANOUT_INFORM, BuiltinExchangeType.FANOUT);
            channel.queueBind(QUEUE_INFORM_EMAIL,EXCHANGE_FANOUT_INFORM,"");
            channel.queueBind(QUEUE_INFORM_SMS,EXCHANGE_FANOUT_INFORM,"");
            // 发送消息
            /**
             * arg1:交换机，如果不指定将使用mq得默认交换机
             * arg2:路由key，交换机根据路由key来将消息转发到指定得队列
             * arg3:额外得属性
             * arg4:发送得消息
             */
            for (int i=0;i<50;i++){
                String msg = "Test Mess sed";
                channel.basicPublish(EXCHANGE_FANOUT_INFORM,"",null,msg.getBytes());
                System.out.println("send to mq -> "+msg) ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            channel.close();
            connection.close();

        }

    }

}
